package com.xongxong.admin.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.MathGenerator;
import com.google.common.cache.Cache;
import com.xongxong.admin.common.constants.Constants;
import com.xongxong.admin.service.CodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

@Slf4j
@Service
public class CodeServiceImpl implements CodeService {
    @Resource
    private Cache<String, String> codeToken;


    @Override
    public boolean captcha(String codeKey, String codeValue) {
        String ifPresent = codeToken.getIfPresent(codeKey);
        if (ifPresent==null) {
            throw new RuntimeException("验证码错误请刷新重新输入");
        }
        // 验证码正确
        return ifPresent.equals(codeValue);
    }

    @Override
    public String saveCode(String code)  {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        // 自定义验证码内容为四则运算方式
        lineCaptcha.setGenerator(new MathGenerator());
        // 重新生成code
        lineCaptcha.createCode();
        String imageBase64 = lineCaptcha.getImageBase64();
        // 生成的验证码图片为
        log.info("imageBase64:{}", imageBase64);
        try {
            String codeKey = lineCaptcha.getCode();
            String expression = codeKey.substring(0, codeKey.length() - 1);
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("JavaScript");
            Object eval = engine.eval(expression);
            codeToken.put(code,  eval.toString());
            return Constants.CachStatusEnum.JPEG.getDesc() +imageBase64;
        } catch (Exception e) {
            throw new RuntimeException("根据算试-计算结果出现异常,信息为:{}"+e.getMessage());
        }
    }
}
